package com.example.captcha.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.captcha.model.Captcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RequestMapping("captcha")
@RestController
public class CaptchaController {
    private final static long session_volid_timeout=60*1000;
    @Autowired
    private Captcha captcha;
    @RequestMapping("/get")
    public void getCaptcha(HttpSession session,HttpServletResponse response){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captcha.getWidth(), captcha.getHeight());
        try {
            lineCaptcha.write(response.getOutputStream());
            session.setAttribute(captcha.getSession().getKey(),lineCaptcha.getCode());
            session.setAttribute(captcha.getSession().getDate(),System.currentTimeMillis());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    @RequestMapping("/check")
    public Boolean checkCaptcha(String inputCode,HttpSession session){
        if(!StringUtils.hasLength(inputCode)){
            return false;

        }
        String key=(String) session.getAttribute(captcha.getSession().getKey());
        long date=(long)session.getAttribute(captcha.getSession().getDate());
        if(inputCode.equals(key)&&key!=null&&System.currentTimeMillis()-date< session_volid_timeout){
            return  true;
        }
        return false;
    }
}
